<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="iOS StoryBoard 优雅创建控制器方式我的项目中使用到了StoryBoard, 我也是喜欢上了这种创建页面的方式, 所见即所得, 每当产品让我改页面的时候, 我都说分分钟就好. 不用在一坨代码中找一个label, 然后修改其颜色, 改颜色几秒钟, 找代码却找了两分钟. StoryBoard的优点 创建快, 容易上手 页面直观 页面逻辑关系清晰 TableViewController的St">
<meta name="keywords" content="Tech,iOS,Swift">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS StoryBoard 优雅创建控制器方式">
<meta property="og:url" content="http://mybadge.vip/2018/08/12/storyboard/index.html">
<meta property="og:site_name" content="mybadge">
<meta property="og:description" content="iOS StoryBoard 优雅创建控制器方式我的项目中使用到了StoryBoard, 我也是喜欢上了这种创建页面的方式, 所见即所得, 每当产品让我改页面的时候, 我都说分分钟就好. 不用在一坨代码中找一个label, 然后修改其颜色, 改颜色几秒钟, 找代码却找了两分钟. StoryBoard的优点 创建快, 容易上手 页面直观 页面逻辑关系清晰 TableViewController的St">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-12-12T14:24:55.291Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS StoryBoard 优雅创建控制器方式">
<meta name="twitter:description" content="iOS StoryBoard 优雅创建控制器方式我的项目中使用到了StoryBoard, 我也是喜欢上了这种创建页面的方式, 所见即所得, 每当产品让我改页面的时候, 我都说分分钟就好. 不用在一坨代码中找一个label, 然后修改其颜色, 改颜色几秒钟, 找代码却找了两分钟. StoryBoard的优点 创建快, 容易上手 页面直观 页面逻辑关系清晰 TableViewController的St">






  <link rel="canonical" href="http://mybadge.vip/2018/08/12/storyboard/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>iOS StoryBoard 优雅创建控制器方式 | mybadge</title>
  



	<div id="vk_api_transport"></div>
	<script type="text/javascript">
		window.vkAsyncInit = function() {
			VK.init({
				apiId: 6660397
			});

			
				VK.Widgets.Like("vk_like", {type: "mini", height: 20});
			

			
				VK.Widgets.Comments("vk_comments", {limit: 10, attach: "*"});
			
		};
		setTimeout(function() {
			var el = document.createElement("script");
			el.type = "text/javascript";
			el.src = "//vk.com/js/api/openapi.js";
			el.async = true;
			document.getElementById("vk_api_transport").appendChild(el);
		}, 0);
	</script>






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?d837a07aa04213208d738aa9616477f7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">mybadge</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">知识改变命运, 技术改变世界</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://mybadge.vip/2018/08/12/storyboard/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="mybadge">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="mybadge">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">iOS StoryBoard 优雅创建控制器方式
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-08-12 22:22:22" itemprop="dateCreated datePublished" datetime="2018-08-12T22:22:22+08:00">2018-08-12</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-12-12 22:24:55" itemprop="dateModified" datetime="2018-12-12T22:24:55+08:00">2018-12-12</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="iOS-StoryBoard-优雅创建控制器方式"><a href="#iOS-StoryBoard-优雅创建控制器方式" class="headerlink" title="iOS StoryBoard 优雅创建控制器方式"></a>iOS StoryBoard 优雅创建控制器方式</h2><p>我的项目中使用到了<strong>StoryBoard</strong>, 我也是喜欢上了这种创建页面的方式, 所见即所得, 每当产品让我改页面的时候, 我都说分分钟就好. 不用在一坨代码中找一个label, 然后修改其颜色, 改颜色几秒钟, 找代码却找了两分钟.</p>
<h3 id="StoryBoard的优点"><a href="#StoryBoard的优点" class="headerlink" title="StoryBoard的优点"></a>StoryBoard的优点</h3><ul>
<li>创建快, 容易上手</li>
<li>页面直观</li>
<li>页面逻辑关系清晰</li>
<li>TableViewController的Static.Cell功能</li>
</ul>
<h3 id="StoryBoard的缺点"><a href="#StoryBoard的缺点" class="headerlink" title="StoryBoard的缺点"></a>StoryBoard的缺点</h3><ul>
<li>StoryBoard内容多的时候加载慢, 这个是所有程序员所不能忍受的.</li>
<li>StoryBoard的segue乱, 页面少的时候还好, 一旦多起来,那个线会像蜘蛛网一样, 蜘蛛网还好, 还是有规律的, StoryBoard就是乱的不得了了</li>
<li>StoryBoard的segue不灵活, 使用起来比较麻烦, 需要配置segue.identifier, 属于是硬编码, 有时候很容易配置错</li>
<li>页面间传递参数的时候麻烦, 一个方法里写跳转逻辑, 另一个方法里写参数传递, 一个控制中多个跳转的时候, 还要判断segue.identifier 这种写法我真的是受不了.</li>
<li>UIStoryBoard方式创建麻烦, 创建控制器之前先创建一个UIStoryBoard对象, 然后在根据StoryBoard.identifier去创建, 标识符的配置,也是硬编码.</li>
</ul>
<h3 id="优雅的使用StoryBoard"><a href="#优雅的使用StoryBoard" class="headerlink" title="优雅的使用StoryBoard"></a>优雅的使用StoryBoard</h3><p>基于以上的啰嗦, 我在想是不是可以, 像纯代码创建控制器的方式那样创建StoryBoard的VC呢, 像 CustomViewController.creatVC() 这样是不是就和原来的用法一样了, 既然想到了, 那就去实现以下吧, 正好可以用Swift来实现一下. 想要的效果</p>
<pre><code>let vc = CustomViewController.creatVC()
vc.model = model
navigationController?.pushViewController(vc, animated: true)
</code></pre><h3 id="我的思路"><a href="#我的思路" class="headerlink" title="我的思路"></a>我的思路</h3><ul>
<li>分模块拆分StoryBoard, 这样可以减少StoryBoard的体积, 避免加载慢的问题</li>
<li>segue只是做业务之间的逻辑显示, 不用它来做跳转, 或者不用它</li>
<li><p>StoryBoard.identifier的约定, 约定所有的StoryBoard.identifier为控制器类名, 方便统一创建VC, 也不用纠结叫什么, 主要也是怕失误的时候写错, 我一般是写上类名的时候, 直接copy一下类名放到identifier上.</p>
<pre><code>let sb = UIStoryboard(name: &quot;storyBoardName&quot;, bundle: nil)
   let vc = sb.instantiateViewController(withIdentifier: &quot;storyboardId&quot;) as! CustomerController
</code></pre></li>
<li>根据以上代码分析出需要, storyBoardName, storyboardId, 两个变量, storyboardId就是类名, 可以直接通过类名获得, 但是这个storyBoardName怎么获取呢?</li>
<li>通过属性, 好像是不行, 因为创建控制之前还没有属性, 类属性, 我也不想每个控制器都写一下, 而且也觉得不是一个好的方法, 接下来我就想到了用协议, 协议中定义一个方法, 让它返回StoryBoard name.</li>
</ul>
<h3 id="我的实现"><a href="#我的实现" class="headerlink" title="我的实现"></a>我的实现</h3><pre><code>/// 这里可以把StoryBoard以模块划分,
enum StoryBoardName: String {
    case none = &quot;&quot;
    case main = &quot;Main&quot;
    case project = &quot;Project&quot;
    case login = &quot;Login&quot;
    case other = &quot;Other&quot;
    case mine = &quot;Mine&quot;
}

protocol StoryBoardDelegate {
    static func storyBoardName() -&gt; StoryBoardName
}

protocol ClassNameDelete {
    static func className() -&gt; String
}


extension UIViewController: ClassNameDelete {
    static func className() -&gt; String {
        if let className = classForCoder().description().components(separatedBy: &quot;.&quot;).last {
            return className
        } else {
            return classForCoder().description().components(separatedBy: &quot;.&quot;).first!
        }
    }
}


extension BaseViewController {

    /// 通用创建VC方式
    class func creatVC() -&gt; Self {

        let type = self.storyBoardName()
        if type == .none {
            return self.init()
        } else {
            if let vc = UIStoryboard.initVC(classType: self) {
                return vc
            } else {
                debugPrint(&quot;className=\(className())创建失败&quot;)
                return self.init()
            }
        }
    }
}

extension UIStoryboard {
    /// 根据类名创建 由StoryBoard 创建的控制器.
    class func initVC&lt;T&gt;(classType: T.Type) -&gt; T? where T: ClassNameDelete, T: StoryBoardDelegate {
        let name = T.storyBoardName()
        let sb = UIStoryboard.init(name: name.rawValue, bundle: nil)
        let vc = sb.instantiateVC(classType: classType)
        return vc
    }

    func instantiateVC&lt;T&gt;(classType: T.Type) -&gt; T? where T: ClassNameDelete {
        let className = T.className()
        let vc = instantiateViewController(withIdentifier: className)
        return vc as? T
    }
}
</code></pre><h3 id="具体使用"><a href="#具体使用" class="headerlink" title="具体使用"></a>具体使用</h3><pre><code>/// 在基类中实现这个协议
class BaseViewController: UIViewController, StoryBoardDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    class func storyBoardName() -&gt; StoryBoardName {
        return .none
    }
} 

/// 子类中实现, 若是纯代码方式创建则不需要实现这个方法.
class TestView1Controller: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = &quot;TestView1&quot;
    }

    override static func storyBoardName() -&gt; StoryBoardName {
        return .main
    }

    @IBAction func btnToTest2Action(_ sender: UIButton) {
        let vc = TestView2Controller.creatVC()
        navigationController?.pushViewController(vc, animated: true)
    }
}
</code></pre><h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>自我感觉使用起来比较方便, 若是谁有更好的方式, 或可以优化的地方, 欢迎交流.<br><a href="https://github.com/mybadge/CreatVCDemo" target="_blank" rel="noopener">代码Demo</a></p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Tech/" rel="tag"># Tech</a>
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
            <a href="/tags/Swift/" rel="tag"># Swift</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        
          <div class="social-like">
            
              <div class="vk_like">
                <span id="vk_like"></span>
              </div>
            

            
          </div>
        

        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/15/block的深度理解/" rel="next" title="深度理解Block">
                <i class="fa fa-chevron-left"></i> 深度理解Block
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/12/12/swift-gcd/" rel="prev" title="GCD 了解一下">
                GCD 了解一下 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="vk_comments"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">mybadge</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">2</span>
                    <span class="site-state-item-name">分类</span>
                  
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">标签</span>
                  
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#iOS-StoryBoard-优雅创建控制器方式"><span class="nav-number">1.</span> <span class="nav-text">iOS StoryBoard 优雅创建控制器方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#StoryBoard的优点"><span class="nav-number">1.1.</span> <span class="nav-text">StoryBoard的优点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#StoryBoard的缺点"><span class="nav-number">1.2.</span> <span class="nav-text">StoryBoard的缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优雅的使用StoryBoard"><span class="nav-number">1.3.</span> <span class="nav-text">优雅的使用StoryBoard</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#我的思路"><span class="nav-number">1.4.</span> <span class="nav-text">我的思路</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#我的实现"><span class="nav-number">1.5.</span> <span class="nav-text">我的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#具体使用"><span class="nav-number">1.6.</span> <span class="nav-text">具体使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">1.7.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">mybadge</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Gemini</a> v6.3.0</div>





        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



  





  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
